<template>
  <page-layout>
    <div slot="toolbar">
      <!--<el-button size="small" round type="info" @click="goBack">返回视频管理</el-button>-->
      <el-button size="small" round type="primary" @click="newQuestion">新增练习题</el-button>
    </div>
    <div class="card-header">普通题库管理</div>
    <el-card class="box-card ">
      <el-row :gutter="5">
        <el-col :span="4">
          <el-table
            :data="questionClassList" border stripe
            highlight-current-row
            @selection-change="handleSelectionClassChange" row-class-name="link">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="clazz"
              label="分类"
            >
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="20">
          <el-card class="box-card">
            <el-row>
              <el-col :span="24">
                <el-form ref="searchQuestionCondition" :model="searchQuestionCondition" label-width="80px" inline>
                  <el-form-item label="标题">
                    <el-input v-model="searchQuestionCondition.title" style="width: 300px;"/>
                  </el-form-item>
                  <el-form-item label="题目类型">
                    <el-select v-model="searchQuestionCondition.type" placeholder="请选择" style="width: 300px;">
                      <el-option
                        v-for="item in UserTypes"
                        :key="item.value"
                        :label="item.text"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button type="primary" @click="importQuestion">导入题库</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="box-card">
            <el-table
              :data="questionList.content" border stripe
              style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="题目">
                      <span>{{ props.row.title }}</span>
                    </el-form-item>
                    <el-form-item label="题目类型">
                      <span >{{props.row.type|keyText('UserTypes')}}</span>
                    </el-form-item>
                    <el-form-item label="分数">
                      <span>{{ props.row.score }}</span>
                    </el-form-item>
                    <el-form-item label="选项">
                      <span v-html="getOptions(props.row.options)"></span>
                    </el-form-item>
                    <el-form-item label="答案">
                      <span>{{ props.row.answer }}</span>
                    </el-form-item>
                    <el-form-item label="答题总数">
                      <span>{{ props.row.count }}</span>
                    </el-form-item>
                    <el-form-item label="正确率">
                      <span>{{ props.row.correctRate }}</span>
                    </el-form-item>
                    <el-form-item label="解析">
                      <span>{{ props.row.analysis }}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column
                prop="id"
                label="编号"
                width="55">
              </el-table-column>

              <el-table-column prop="title" label="题目" ></el-table-column>
              <el-table-column
                prop="options"
                label="选项" >
                <template slot-scope="scope">
                  <span v-html="getOptions(scope.row.options)"></span>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="分类" >
                <template slot-scope="scope">
                  <span >{{scope.row.type|keyText('UserTypes')}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="clazzs" label="题库分类" >
                <template slot-scope="scope">
                  <span v-html="getClazz(scope.row.clazzs)"></span>
                </template>
              </el-table-column>
              <el-table-column prop="answer" label="答案" ></el-table-column>
              <el-table-column prop="analysis" label="题目解析" ></el-table-column>
              <el-table-column prop="count" label="答题总数" ></el-table-column>
              <el-table-column prop="correctRate" label="正确率" ></el-table-column>
              <el-table-column prop="score" label="积分" ></el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button size="mini"  type="text" @click="editQuestion(scope.$index, scope.row)" >编辑</el-button>
                  <el-button size="mini" type="text" @click="deleteQuestion(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt10">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="questionList.totalElements"
                :page-size="questionList.size"
                :current-page.sync="currentQuestionPage" @current-change="getPageChange">
              </el-pagination>
            </div>
          </el-card>
        </el-col>
      </el-row>

    </el-card>
    <el-dialog :visible.sync="showQuestionEditor" title="添加/编辑 练习题" width="70%">
      <question-editor @close="onQuestionEditorClose"  :is-close="showQuestionEditor"></question-editor>
    </el-dialog>
    <el-dialog title="导入" :visible.sync="dialogImportVisible" :modal-append-to-body="false" :close-on-click-modal="false" class="dialog-import">
      <div :class="{'import-content': importFlag === 1, 'hide-dialog': importFlag !== 1}">
        <el-upload class="upload-demo"
                   :action="uploadUrl"
                   ref="importData"
                   :auto-upload="autoUpload"
                   :headers="importHeaders"
                   :before-upload="beforeUpload"
                   :data="postData"
                   :limit="1"
                   :on-change="fileChange"
                   :on-success="uploadSuccess"
                   :file-list="fileList"
        >
          <!-- 是否支持发送cookie信息 -->
          <el-button size="small" type="primary" :disabled="processing">{{uploadTip}}</el-button>
          <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
        </el-upload>
      </div>
      <div :class="{'import-failure': importFlag === 2, 'hide-dialog': importFlag !== 2}" >
        <div class="failure-tips">
          <i class="el-icon-warning"></i>导入失败</div>
        <div class="failure-reason">
          <h4>失败原因</h4>
          <ul>
            <li v-for="(error,index) in errorResults" :key="index">第{{error.rowIdx + 1}}行，错误：{{error.column}},{{error.value}},{{error.errorInfo}}</li>
          </ul>
        </div>
      </div>
    </el-dialog>
  </page-layout>
</template>
<script>
import PageLayout from "@/components/page-layout";
import QuestionEditor from "./question-editor";
import { mapGetters } from "vuex";
import ImageCover from "@/components/image-cover";
import Status from "@/libs/status";
import _ from "lodash";
import Api from "api/api";
import md5 from "js-md5";
export default {
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getPageChange(1);
    });
  },
  created() {
    this.$store.dispatch("getQuestClassListS").then(res => {});
  },
  mounted() {
    this.UserTypes = _.clone(Status.UserTypes);
    this.UserTypes.unshift({ text: "全部", value: "" });
  },
  data() {
    return {
      clazzs: [],
      uploadUrl: this.$appConf.domain.uploadUrl,
      showQuestionClassEditor: false,
      autoUpload: false,
      importHeaders: {
        clientId: "ADMIN",
        token: ""
      },
      key: "",
      name: "import",
      fileList: [],
      withCredentials: true,
      processing: false,
      uploadTip: "点击上传",
      importFlag: 1,
      dialogImportVisible: false,
      errorResults: [],
      currentQuestionPage: 1,
      showQuestionEditor: false,
      postData: {},
      QuestionStatus: Status.QuestionStatus,
      UserTypes: [],
      multipleSelectionS: [],
      uuid: Math.random()
        .toString(36)
        .substring(3, 8)
    };
  },
  computed: {
    ...mapGetters({
      questionList: "questionList",
      questionClassList: "questionClassList",
      searchQuestionCondition: "searchQuestionCondition"
    })
  },
  methods: {
    handleSelectionClassChange(val) {
      this.multipleSelectionS = val;
      if (this.multipleSelectionS) {
        var tem = [];
        this.multipleSelectionS.map((item, index) => {
          tem.push(item.id);
        });
        this.searchQuestionCondition.classIds = tem.join(",");
        this.search();
      }
    },
    importQuestion() {
      this.importFlag = 1;
      this.fileList = [];
      this.uploadTip = "点击上传";
      this.processing = false;
      this.dialogImportVisible = true;
    },
    beforeUpload(file) {
      //上传前配置
      let excelfileExtend = ".xls,.xlsx"; //设置文件格式
      let fileExtend = file.name
        .substring(file.name.lastIndexOf("."))
        .toLowerCase();
      if (excelfileExtend.indexOf(fileExtend) <= -1) {
        this.$message.error("文件格式错误");
        return false;
      }
      this.uploadTip = "正在处理中...";
      this.processing = true;
    },
    fileChange(file, fileList) {
      console.log(222);
      var tmp = `${file.lastModified + file.size + Date.now() + this.uuid}`;
      var nameArr = file.name.split(".");
      var extName = nameArr[nameArr.length - 1];
      var key = md5(tmp) + "." + extName;
      console.log(key, "222");
      this.$store.dispatch("getUploadFileToken", key).then(res => {
        this.importHeaders.token = res.data.data.token;
        this.postData.token = res.data.data.token;
        this.postData.key = res.data.data.key;
        this.autoUpload = true;
        this.$refs.importData.submit();
      });
    },
    //上传成功
    uploadSuccess(res, file) {
      this.uploadTip = "点击上传";
      this.processing = false;
      this.$store
        .dispatch("importQuestionS", { fileName: res.key })
        .then(ret => {
          this.dialogImportVisible = false;
          this.$message.info("导入成功");
          this.search();
        });
    },
    getOptions(options) {
      var tem = options.split("\n");
      var str = "";
      if (tem) {
        tem.map((item, index) => {
          str += "<p>" + item + "</p>";
        });
      }

      return str;
    },
    getClazz(types) {
      var str = "";
      if (types) {
        types.map((item, index) => {
          str += "<p>" + item.clazz + "</p>";
        });
      }
      return str;
    },
    getPageChange(val) {
      console.log(val);
      var tem = Object.assign(
        { pageIndex: val - 1 },
        this.searchQuestionCondition
      );
      this.$store.dispatch("getQuestionPageS", tem).then(ret => {});
    },
    search() {
      this.getPageChange(1);
    },
    deleteQuestion(row) {
      this.$confirm("确认删除当前题目?", "提示", {})
        .then(() => {
          this.$store.dispatch("deleteQuestionS", { id: row.id }).then(ret => {
            this.getPageChange(1);
            this.$notify({
              title: "删除成功",
              type: "success"
            });
          });
        })
        .catch(() => {});
    },
    newQuestion() {
      this.$store.commit("INIT_CURRENT_QUESTION");
      this.showQuestionEditor = true;
    },
    editQuestion(index, row) {
      this.$store.dispatch("getQuestionS", row.id);
      this.showQuestionEditor = true;
    },
    onQuestionEditorClose() {
      this.showQuestionEditor = false;
      this.getPageChange(this.currentQuestionPage);
    },
    onShowPreviewClose() {
      this.showPreview = false;
      this.getPageChange(this.currentQuestionPage);
    }
  },
  components: {
    PageLayout,
    QuestionEditor,
    ImageCover
  }
};
</script>
<style scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.hide-dialog {
  display: none;
}
</style>
